/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package di.persistence.dao.impl;

import di.persistence.dao.DIHibernateDaoSupport;
import di.persistence.dao.UserTypeDao;
import di.persistence.entities.User;
import di.persistence.entities.UserType;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.mapping.Join;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Kilian Ito
 */
@Repository("UserTypeDao")
public class UserTypeDaoImpl extends DIHibernateDaoSupport implements UserTypeDao {
 
    
    @Override
    public void save(UserType userType) throws DataAccessException {
            getHibernateTemplate().save(userType);
    }

    @Override
    public void update(UserType userType) throws DataAccessException {
            getHibernateTemplate().update(userType);
    }

    @Override
    public void delete(UserType userType) throws DataAccessException {
            getHibernateTemplate().delete(userType);
    }
    
    @Override
    public UserType getUserByLabel(final String label) throws DataAccessException {
        return getHibernateTemplate().execute(new HibernateCallback<UserType>() {
            @Override
            public UserType doInHibernate(Session sn) throws HibernateException, SQLException {
                Criteria criteria = sn.createCriteria(UserType.class);
                criteria.add(Restrictions.ilike("label", label));
                criteria.setMaxResults(1);
                return (UserType)criteria.uniqueResult();
            }
        });
    }
    
    @Override
    public List<UserType> getChildren(final UserType userType) throws DataAccessException {
        if (userType.getId() == null)
            return null;
        return getHibernateTemplate().get(UserType.class, userType.getId()).getChildren();
    }
}
